<template>
  <view class="login-container">
    <!-- 标题 -->
    <text class="title">用户登录</text>

    <!-- 用户名输入 -->
    <input
      v-model="userID"
      class="input-field"
      placeholder="请输入用户名"
      :focus="true"
    />

    <!-- 密码输入 -->
    <input
      v-model="password"
      class="input-field"
      placeholder="请输入密码"
      password
      :focus="false"
    />
	
	<!-- 局域网地址管理 -->
	<!-- <input
	  v-model="urlText"
	  class="input-field"
	  placeholder="请输入服务器地址,例:http://192.168.1.148:8080"
	  :focus="true"
	/> -->

    <!-- 登录按钮 -->
    <button
		class="login-btn"
		:loading="isLoading"
		@tap="handleLogin"
    >
		{{ isLoading ? '登录中...' : '登录' }}
    </button>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue';

/* 网络基础配置 */
import { LAN_URL } from '@/pages/config/global'
//let LAN_URL = '';
const LOGIN_URL = '/user/login'
const GETNAME_URL = '/user/username'

/* 响应式状态 */
const userID = ref('');
const password = ref('');
const isLoading = ref(false);
const urlText = ref('');


/* 登录功能 */
const handleLogin = async () => {
	if (!validateInput()) return;
	isLoading.value = true;

	try {
		//执行登录请求
		const loginRes = await uni.request({
			url: `${LAN_URL}${LOGIN_URL}`,
			method: 'POST',
			header: { "Content-Type": "application/x-www-form-urlencoded" },
			data: `userID=${encodeURIComponent(userID.value)}&password=${encodeURIComponent(password.value)}`
		});
		handleLoginResponse(loginRes.data);
	} catch (error) {
		handleLoginError(error);
	} finally {
		isLoading.value = false;
	}
};

/* 登录初步验证 */
const validateInput = () => {
	if (!userID.value.trim()) {
		uni.showToast({ title: '用户名不能为空', icon: 'none' });
		return false;
	}
	if (!password.value.trim()) {
		uni.showToast({ title: '密码不能为空', icon: 'none' });
		return false;
	}
	return true;
};

/* 处理登录响应 */
const handleLoginResponse = (result: number) => {
	switch (result) {
		case 1:
			fetchUserInfo();
			break;
		case -1:
			uni.showToast({ title: '用户名或密码错误', icon: 'none' });
			break;
		case -2:
			uni.showToast({ title: '账号状态无效', icon: 'none' });
			break;
		default:
			uni.showToast({ title: '网络异常，请重试', icon: 'none' });
  }
};

/* 获取用户信息 */
const fetchUserInfo = async () => {
	try {
		const userRes = await uni.request({
			url: `${LAN_URL}${GETNAME_URL}`,
			method: 'POST',
			header: { 'Content-Type': 'application/x-www-form-urlencoded' },
			data: `userID=${encodeURIComponent(userID.value)}`
		});
		
		// 存储用户信息
		const userData = {
			id: userID.value,
			name: userRes.data
		};
			uni.setStorageSync('user', userData);
	
			uni.showToast({ title: '登录成功' });
			setTimeout(() => {
				uni.navigateBack({
					delta: 1
				});
			}, 1000)
			//uni.redirectTo({ url: '@/pages/index/index' });
			//uni.navigateBack();
			
	} catch (error) {
		uni.showToast({ title: '用户信息获取失败', icon: 'none' });
	}
};

/* 登陆错误 */
const handleLoginError = (error: any) => {
  console.error('登录失败:', error);
  uni.showToast({
    title: error.errMsg || '网络连接失败',
    icon: 'none'
  });
};
</script>

<style scoped>
.login-container {
  flex: 1;
  padding: 60rpx 40rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.title {
  font-size: 40rpx;
  color: #333;
  margin-bottom: 80rpx;
  font-weight: bold;
}

.input-field {
  width: 100%;
  height: 100rpx;
  padding: 0 30rpx;
  margin-bottom: 40rpx;
  border-radius: 50rpx;
  background-color: #f5f5f5;
  font-size: 32rpx;
}

.login-btn {
  width: 100%;
  height: 100rpx;
  line-height: 100rpx;
  border-radius: 50rpx;
  background-color: #007AFF;
  color: white;
  font-size: 36rpx;
  margin-top: 60rpx;
}

.login-btn[disabled] {
  background-color: #cccccc;
}
</style>